package com.yyds.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.jdbc.StringUtils;
import com.yyds.yygh.cmn.listener.DictListener;
import com.yyds.yygh.cmn.mapper.DictMapper;
import com.yyds.yygh.cmn.service.DictService;
import com.yyds.yygh.model.cmn.Dict;
import com.yyds.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper,Dict> implements DictService {
    @Autowired
    private DictMapper dictMapper;

    @Cacheable(value = "dict" , keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChlidData(Long id) {
        //根据ID获取儿子的信息
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        List<Dict> dictList = dictMapper.selectList(queryWrapper);
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict : dictList) {
            boolean isChild  = this.hasChildren(dict);
            dict.setHasChildren(isChild );
        }
        return dictList;
    }

    @CacheEvict(value = "dict" , allEntries = true)
    @Override
    public void exportData(HttpServletResponse httpServletResponse) {
        httpServletResponse.setContentType("application/vnd.ms-excel");
        httpServletResponse.setCharacterEncoding("utf-8");
        try {
            String fileName = URLEncoder.encode("数据字典","UTF-8");
            httpServletResponse.setHeader("Content-disposition",
                    "attachment;filename=" + fileName +".xlsx");
            List<Dict> dicts = dictMapper.selectList(null);
            List<DictEeVo> dictEeVos = new ArrayList<>(dicts.size());
            for (Dict dict : dicts) {
                DictEeVo dictEeVo = new DictEeVo();
                //把dict对象中属性数据拷贝给dictVo对象的同名属性
                BeanUtils.copyProperties(dict,dictEeVo);
                dictEeVos.add(dictEeVo);
            }

            //导入
            EasyExcel.write(httpServletResponse.getOutputStream(),DictEeVo.class)
                    .sheet("数据字典").doWrite(dictEeVos);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(dictMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        if (StringUtils.isNullOrEmpty(parentDictCode)){
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("value",value);
            Dict dict = dictMapper.selectOne(queryWrapper);
                return dict.getName();
        }else {
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("dict_code",parentDictCode);
            Dict dict = dictMapper.selectOne(queryWrapper);
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id",dict.getId()).eq("value",value);
            Dict dictOne = dictMapper.selectOne(wrapper);
            return dictOne.getName();
        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code",dictCode);
        Dict parentDict = dictMapper.selectOne(queryWrapper);
        List<Dict> dictList = this.findChlidData(parentDict.getId());
        return dictList;
    }

    //查询是否有Children
    private boolean hasChildren(Dict dict){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",dict.getId());
        Integer integer = dictMapper.selectCount(queryWrapper);
        return integer > 0;
    }
}
